package cn.itlaobing.springbootdemo;


import cn.itlaobing.springbootdemo.web.filter.AuthenticationInterceptor;
import cn.itlaobing.springbootdemo.web.filter.SiteMeshFilter;
import cn.itlaobing.springbootdemo.web.listener.ApplicationContextListener;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class ApplicationConfiguration extends WebMvcConfigurerAdapter{
    /**
     * 相当于在xml文件中配置了一个bean
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean siteMeshFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new SiteMeshFilter());
        filterRegistrationBean.setEnabled(true);
        filterRegistrationBean.setName("siteMeshFilter");
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

    /**
     * 注册Servlet  使用 ServletRegistrationBean
     * 注册Listener 使用 ServletListenerRegistrationBean
     */

    @Bean
    public ServletListenerRegistrationBean<ApplicationContextListener> contextPathListener(){
        ServletListenerRegistrationBean<ApplicationContextListener> servletListenerRegistrationBean=new ServletListenerRegistrationBean<>();
        servletListenerRegistrationBean.setListener(new ApplicationContextListener());
        servletListenerRegistrationBean.setName("contextPathListener");
        return servletListenerRegistrationBean;
    }


    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthenticationInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/signin","/assets/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //  <mvc:resources mapping="/assets/**" location="/assets/" />
        registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
    }
}
